
# -*- coding:utf-8 -*-
import logging
import time
import sys

from btfxwss import BtfxWss

log = logging.getLogger(__name__)

fh = logging.FileHandler('test.log')
fh.setLevel(logging.DEBUG)
sh = logging.StreamHandler(sys.stdout)
sh.setLevel(logging.DEBUG)

log.addHandler(sh)
log.addHandler(fh)
logging.basicConfig(level=logging.DEBUG, handlers=[fh, sh])

wss = BtfxWss()
wss.start()

connectTime = 1
while not wss.conn.connected.is_set():
    print("socket连接错误，第" + str(connectTime) + "重新连接中...")
    connectTime += 1
    time.sleep(1)

# Subscribe to some channels
print("订阅ticker数据...")
wss.subscribe_to_ticker('BTCUSD')
print("订阅book数据...")
wss.subscribe_to_order_book('BTCUSD', prec = 'P0')

# Do something else
waitTime = 10
print("休息" + str(waitTime) + "秒")
t = time.time()
while time.time() - t < waitTime:
    pass
print("休息" + str(waitTime) + "秒结束")


# Accessing data stored in BtfxWss:
dataID = 1
validDataID = 1
t = time.time()
while time.time() - t < 30:
    #print('-' * 30)
    #print(str(dataID) + "\t号数据:")
    ticker_q = wss.tickers('BTCUSD')  # returns a Queue object for the pair.
    book_q = wss.books("BTCUSD")
    # print("本次获取的数据内容为：")


    while not ticker_q.empty():
         print(str(dataID) + "\t号数据:")
         print(ticker_q.get())
         print(str(dataID) + "\t号数据消费完毕")
         dataID += 1
    '''
    while not book_q.empty():
        print(book_q.get())
    '''


    # 当数据消费完毕以后，暂停等待下次获取

    time.sleep(0.1)


print("打印数据结束")
# Unsubscribing from channels:
wss.unsubscribe_from_ticker('BTCUSD')
wss.unsubscribe_from_order_book('BTCUSD')

# Shutting down the client:
wss.stop()